package com.tuo51.components.intercepter;

import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;

@Slf4j
public class OPAuthInterceptor implements HandlerInterceptor {

    @Autowired
    MemVerificationCache cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String ticket = request.getHeader(TICKET);
        if(StringUtils.isEmpty(ticket)){
            throw new BusinessException(ErrorCode.TICKET_REQUIRED, "你无权访问该系统！");
        }else if( (ticket.length() > 34 && !ticket.substring(32, 35).equals("-6-"))
                || cache.getCacheMap(ticket) == null){
            throw new BusinessException(ErrorCode.TICKET_REQUIRED, "非系统授权ticket！");
        }

        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("OPAuthInterceptor ::: postHandle");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("OPAuthInterceptor ::: afterCompletion");
//    }
}
